import DataStore from '../base/DataStore';
import Sprite from '../base/Sprite'
import RoleAction from '../../../Enum/roleAction'

/**
    角色基类, 
        控制位置
        不负责绘制图形

    静止
    走动
    左右
    跑
    跳
*/
class Role extends Sprite{
    constructor(...props) {
        super(...props)
        this.dataStore = DataStore.getInstance();
        this.ctx = this.dataStore.ctx;
        this.canvas = this.dataStore.canvas;
        this.gameConf = this.dataStore.get('gameConf');
        this.roleConf = this.dataStore.get('roleConf');
        // 坠落的时间
        this.time = 0;

        // 角色状态
        this.status = RoleAction[0]; // 默认静止
        this.direction = 'left';     // 方向

        // 初始化角色主体
        this.width = 74;
        this.height = 100;
        this.bodyCenter = this.width / 2;
        this.x = 0;
        this.y = this.canvas.height - this.height;
        this.actionMap = {
            'backward': () => this.move(-1),
            'forward': () => this.move(1),
            'stand': () => this.stand(),
        }
    }
    move(num) {
        if (num > 0) {
            this.status = RoleAction[5];
            this.x += this.gameConf.moveSpeed * 1.5;
        } else {
            this.x -= this.gameConf.moveSpeed * 1.5;
            this.status = RoleAction[4];
        }
        this.stand();
    }
    stand() {
        let staticRole = this.roleConf[this.roleKey][this.status];
        if (this.index >= staticRole.length - 1) {
            this.index = 0;
        }
        let maxH = Math.max(...staticRole.map(img => img.H));
        let imgData = staticRole[Math.floor(this.index)];
        const { x, y, W, H } = imgData;
        this.width = W;
        this.height = maxH;
        
        if (this.x > this.canvas.width - W) {
            this.x = this.canvas.width - W;
        }
        if (this.x < 0) {
            this.x = 0;
        }
        this.y = this.canvas.height - maxH;
        this.ctx.drawImage(this.img, x, y - (maxH - H), W, this.height, this.x, this.y, W, this.height);
        this.index += this.gameConf.spriteSpeed;
    }
    backOff() {

    }
    squatDown() {

    }
    jump() {
        if (this.status !== RoleAction[5]) {
            this.status = RoleAction[5];
        }
    }
    run() {
        let userAction = this.dataStore.get('keyCodeList');
        if (userAction && userAction.keyCode) {
            const { keyCode } = userAction;
            let action = this.gameConf.keybord[keyCode];
            if (action in this.actionMap) {
                this.actionMap[action]();
                return;
            } 
        }
        this.status = RoleAction[0];
        this.actionMap['stand']();
    }
    show() {
        this.run();

        // 绘制角色轮廓
        // this.ctx.strokeStyle = 'red'
        // this.ctx.strokeRect(
        //     this.x, this.y,
        //     this.width, this.height
        // )
    }
}

export default Role;
